//
//  JYSearchViewController.m
//  JYFarm
//
//  Created by 花花 on 2017/10/10.
//  Copyright © 2017年 花花. All rights reserved.
//

#import "JYSearchViewController.h"
#import "JYSearchBar.h"
#import "JYSearchHistoryView.h"
#import "JYSearchHistoryCell.h"
#import "JYSearchListController.h"
#import "JYSearchHistoryManager.h"
#import "JYPublicCell.h"
@interface JYSearchViewController ()<UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout>
@property(nonatomic) UIView *navBarView;
@property(nonatomic) JYSearchBar *searchBar;

@property(nonatomic) UIButton *searchButton;

@property(nonatomic) UIButton *backBtn;

@property(nonatomic)JYSearchHistoryView *searchHistoryView; //历史记录


@property(nonatomic)UICollectionView *collectionView; //collectionView

@property(nonatomic)NSString *searchName; //搜索的name值

@end

static NSString *const SearchListCellID = @"SearchListCellID";
static NSString *const SearchHistoryCellID = @"SearchHistoryCellID";
@implementation JYSearchViewController

#pragma mark - Life Cycle
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    self.navigationController.navigationBar.hidden = YES;
    
      [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshHistory) name:kSaveHistoryItemSuccessNotification object:nil];
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    self.navigationController.navigationBar.hidden = NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];

  
    
    [self setupNav];
    [self initConstraint];
    [self.view addSubview:self.searchHistoryView];
    [self.view addSubview:self.collectionView];
    
    
//    [self loadDataFromNetwork];
}
- (NSMutableArray *)dataArr{

    if (_dataArr == nil) {
        
        
        _dataArr = [[JYSearchHistoryManager shareInstance]getSearchHistoryArray];
        //缓存为空则初始化
        if (_dataArr == nil) {
            
            _dataArr = [NSMutableArray array];
        }
    }
    return _dataArr;
}
//- (void)loadDataFromNetwork{
//
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshHistory) name:kSaveHistoryItemSuccessNotification object:nil];
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshHistory) name:kClearSearchHistoryNotification object:nil];
//    NSArray * titles = @[@"安庆六白猪",@"北京全聚德烤鸭",@"湘西米粉",@"安庆六白猪",@"北京全聚德烤鸭",@"湘西米粉",@"安庆六白猪",@"北京全聚德烤鸭",@"湘西米粉"];
//    NSArray *IDArr = @[@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"10"];
//    for (int i = 0; i<titles.count; i++)
//    {
//        JYSearchModel * model = [[JYSearchModel alloc]init];
//        model.name = self.searchName;
////        model.ID = IDArr[i];
//        model.nameWidth = [model.name widthForHeight:14 andFont:12];
//        
//        [[JYSearchHistoryManager shareInstance] saveSearchItemToHistory:model];
//        [self.dataArr addObject:model];
//    }
//
//}
- (void)refreshHistory{

//    self.dataArr = [[JYSearchHistoryManager shareInstance] getSearchHistoryArray];
    
    
    [self.collectionView reloadData];
    
    
    self.searchHistoryView.noHistoryLablel.hidden = self.dataArr.count>0?YES:NO;
    

}

- (void)setupNav{
    self.navBarView = [[UIView alloc] init];
    self.navBarView.backgroundColor = kfColor;
    [self.view addSubview:self.navBarView];
    
    
    
    self.searchBar = [[JYSearchBar alloc]initWithOffSet:40];
    self.searchBar.searchEnable = true;
    [self.searchBar.textFiled becomeFirstResponder];
//    self.searchBar.offset = 12;
    self.searchBar.textFiled.text = nil;

    [self.navBarView addSubview:self.searchBar];
    JYWeakSelf;
    self.searchBar.searchBarInputCallBack = ^(NSString *inputString){
        NSLog(@"inputString___%@",inputString);
        weakSelf.searchName = inputString;
        
    };
    
    self.backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.backBtn setImage:[UIImage imageNamed:@"navigationbar_back"] forState:UIControlStateNormal];
    self.backBtn.imageEdgeInsets = UIEdgeInsetsMake(20, -10, 0, 0);
    [self.navBarView addSubview:self.backBtn];
    [self.backBtn addTarget:self action:@selector(backOnClick) forControlEvents:UIControlEventTouchUpInside];
    
    self.searchButton = [[UIButton alloc] init];
    [self.searchButton setTitle:@"搜索" forState:UIControlStateNormal];
    [self.searchButton setTitleColor:[UIColor colorWithHexString:@"666666"] forState:UIControlStateNormal];
    self.searchButton.titleLabel.font = kFont(14);
    self.searchButton.titleEdgeInsets = UIEdgeInsetsMake(15, 0, 0, 0);
    [self.searchButton addTarget:self action:@selector(searchOnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.navBarView addSubview:self.searchButton];




}
- (void)initConstraint{
    JYWeakSelf;
    [self.navBarView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(weakSelf.view.mas_left);
        make.right.equalTo(weakSelf.view.mas_right);
        make.top.equalTo(weakSelf.view.mas_top);
        make.height.equalTo(@64);
    }];
    
    [self.backBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(weakSelf.view.mas_left);
        make.top.equalTo(weakSelf.view.mas_top);
        make.width.equalTo(@60);
        make.height.equalTo(@64);
    }];
    [self.searchButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(weakSelf.view.mas_right);
        make.top.equalTo(weakSelf.view.mas_top);
        make.width.equalTo(@60);
        make.height.equalTo(@64);
    }];
    
    [self.searchBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(weakSelf.navBarView.mas_left);
        make.right.equalTo(weakSelf.searchButton.mas_left).offset(15);
        make.top.equalTo(weakSelf.navBarView.mas_top);
        make.height.equalTo(@64);
    }];

    

}
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    
    return self.dataArr.count;
}

//设置collectionView 的Cell
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{

    
        JYSearchHistoryCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:SearchHistoryCellID forIndexPath:indexPath];
        cell.model = [self.dataArr safeObjectAtIndex:indexPath.row];
        return cell;
}


//Cell
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
   
    NSLog(@"indexPath%zd",indexPath.row);
    [self searchList];
}


//每个item的尺寸
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (self.dataArr.count==0) return CGSizeZero;
    CGFloat itemW = (Screen_Width-5*10)/4;
    
    return CGSizeMake(itemW,25);

}



//设置每个item的UIEdgeInsets
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(0,10,10,10);

}

//设置每个item的水平间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    
    return 0;
}

//设置每个item垂直间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    
    return 10;
}


- (UICollectionView *)collectionView{

    if (!_collectionView) {
        UICollectionViewFlowLayout *layot = [[UICollectionViewFlowLayout alloc]init];
        
        _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(self.searchHistoryView.frame), Screen_Width,100) collectionViewLayout:layot];
        [_collectionView registerClass:[JYSearchHistoryCell class] forCellWithReuseIdentifier:SearchHistoryCellID];
        _collectionView.backgroundColor = [UIColor whiteColor];
        _collectionView.dataSource = self;
        _collectionView.delegate = self;
    }
    return _collectionView;

}
- (JYSearchHistoryView *)searchHistoryView{

    if (!_searchHistoryView) {
      
        _searchHistoryView = [[JYSearchHistoryView alloc]init];
        _searchHistoryView.noHistoryLablel.hidden = (self.dataArr.count>0?YES:NO);
        _searchHistoryView.frame = CGRectMake(0, 65, Screen_Width, 40);
        _searchHistoryView.backgroundColor =[UIColor whiteColor];
        JYWeakSelf;
        
        [_searchHistoryView setEmptySearchHistoryOnClick:^{
            NSLog(@"清空数据");
            
            
            [[JYSearchHistoryManager shareInstance]clearAllSearchHistory];
            weakSelf.searchHistoryView.height = 40;
            weakSelf.searchHistoryView.noHistoryLablel.hidden = NO;
            [weakSelf.collectionView reloadData];
       
        }];
    }
    return _searchHistoryView;

}

- (void)searchList{

    
    [self.searchHistoryView removeFromSuperview];
    [self.collectionView removeFromSuperview];

    [self.view addSubview:self.tableView];
}

- (UITableView *)tableView{
    
    if (!_tableView) {
        
        
        _tableView =  [[UITableView alloc] initWithFrame:CGRectMake(0, 65, Screen_Width,Screen_Height-65)];
        
        _tableView.backgroundColor = [UIColor greenColor];
        _tableView.decelerationRate = UIScrollViewDecelerationRateFast;
        _tableView.decelerationRate = 0.1;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        [self.tableView registerNib:[UINib nibWithNibName:@"JYPublicCell" bundle:nil] forCellReuseIdentifier:SearchListCellID];
        self.tableView.rowHeight = 85;
        
    }
    return _tableView;
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return 20;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    JYPublicCell *cell =[tableView dequeueReusableCellWithIdentifier:SearchListCellID];
    cell.nameLabel.text = [NSString stringWithFormat:@"有机空心心心菜有机空心心心菜%zd",arc4random_uniform(50)];
    cell.count.text = [NSString stringWithFormat:@"%zd",arc4random_uniform(44)];
    cell.imgView.image = [UIImage imageNamed:@"home_icon_wine"];
    cell.priceLabel.text = [NSString stringWithFormat:@"￥%zd/个",arc4random_uniform(150)];
    cell.oldPriceLabel.text = [NSString stringWithFormat:@"￥%zd",arc4random_uniform(100000)];
    
    return cell;
    
}


- (void)backOnClick{

   [self.navigationController popViewControllerAnimated:YES];
}
- (void)searchOnClick{

    NSLog(@"searchName:%@",self.searchName);
    if (self.searchName.length !=0 ) {
        JYSearchModel *model = [JYSearchModel initWithName:self.searchName];

        [[JYSearchHistoryManager shareInstance] saveSearchItemToHistory:model];
         
          [self.dataArr addObject:model];
    }
    [self.collectionView reloadData];
    
    [self searchList];

//    [self.navigationController pushViewController:[JYSearchListController new] animated:YES];
   
    NSLog(@"%s",__func__);
    
}


@end
